'''
Author: your name
Date: 2021-06-25 11:53:51
LastEditTime: 2021-11-05 17:08:09
LastEditors: Please set LastEditors
Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
FilePath: /tinyms/tinyms-api/apps/utils/TypeUtils.py
'''
import json
from sqlalchemy.orm import class_mapper
import numpy as np

'''
类型转换工具类
'''
class TypeUtils():
    '''
    将单个model对象转化为dict方便转为json
    '''
    def object_to_dict(model):
        columns = [c.key for c in class_mapper(model.__class__).columns]
        object_dict = dict((c, getattr(model, c)) for c in columns)
        return object_dict
    

    '''
    将list集合转化为字典
    '''
    def list_to_dict(model):
        result = {}
        columns = [c.key for c in class_mapper(model.__class__).columns]
        for key in columns:
            if getattr(model, key) is not None:
                result[key] = str(getattr(model, key))
            else:
                result[key] = getattr(model, key)
        return result
    
    '''
    list转化为json
    '''
    def list_to_json(lists):
        keys = [str(x) for x in np.arange(len(lists))]
        list_json = dict(zip(keys, lists))
        str_json = json.dumps(list_json, indent=2, ensure_ascii=False)  # json转为string
        return str_json